#!/usr/bin/env bash

set -eu
set -o pipefail

if ! let "$PULL_REQUEST_NUMBER > 0"; then
    cat -
    echo "not pull request" >&2
    exit 0
fi

comment_to_github() {
    local -r message_fd="$1"

    curl -sL -X POST \
        -H "Content-type: application/json" \
        -H "Accept: application/vnd.github.v3+json" \
        -H "Authorization: token $GITHUB_API_TOKEN" \
        -d "$(cat $message_fd)" \
            "https://api.github.com/repos/$PROJECT_SLUG/issues/$PULL_REQUEST_NUMBER/comments"
}

edit_github_comment() {
    local -r message_fd="$1" comment_id="$2"

    curl -sL -X POST \
        -H "Content-type: application/json" \
        -H "Accept: application/vnd.github.v3+json" \
        -H "Authorization: token $GITHUB_API_TOKEN" \
        -d "$(cat $message_fd)" \
            "https://api.github.com/repos/$PROJECT_SLUG/issues/comments/$comment_id"
}

get_comments() {
    curl -sL -X GET \
        -H "Content-type: application/json" \
        -H "Accept: application/vnd.github.v3+json" \
        -H "Authorization: token $DANGER_GITHUB_API_TOKEN" \
            "https://api.github.com/repos/$PROJECT_SLUG/issues/$PULL_REQUEST_NUMBER/comments"
}

parse_comment_id() {
    cat - | jq -r '.[] | select(.body | test("<!-- parse_dg_response=true -->")) | .id'
}

parse_response() {
    local -r response="$(cat -)"

    if [[ $(echo $response | jq ".error") != "false" ]]; then
        # any error happened so it should be out as it is but to stderr
        echo $response >&2
    else
        distribution_url=$(echo $response | jq -r ".results.distribution.url")

        local comment_id=$(get_comments | parse_comment_id)

        if [[ -n "${comment_id:-}" ]]; then
            edit_github_comment <(jq -n --arg body "Try it via $distribution_url <!-- parse_dg_response=true -->" '{ "body": $body }') "$comment_id"
        else
            comment_to_github <(jq -n --arg body "Try it via $distribution_url <!-- parse_dg_response=true -->" '{ "body": $body }')
        fi

        echo $response
    fi
}

cat - | parse_response